﻿<%@ WebHandler Language="C#" Class="DbBackUp" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
public class DbBackUp : IHttpHandler, IRequiresSessionState
{
    Spring.Context.IApplicationContext appContext = Spring.Context.Support.ContextRegistry.GetContext();
    GONES.Tools.Common.LoginInfo loginInfo = new GONES.Tools.Common.LoginInfo();
    public string ErrMsg { get; set; }
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string title = context.Request["title"];
        string url = context.Request.UrlReferrer.AbsolutePath;
        string dbname = GONES.Tools.Common.GlobalSettings.Instance.DbName;
        string _path = GONES.Tools.Common.GlobalSettings.Instance.BackPath;
        string basepath = context.Server.MapPath(_path);
        string dbackname = dbname + "_" + DateTime.Now.ToString("yyyyMMdd");
        string backpath = basepath + dbackname;
        if (!Directory.Exists(basepath))
            Directory.CreateDirectory(basepath);

        if (File.Exists(backpath))
            File.Delete(backpath);
        
        if (context.Session["LoginInfo"] != null)
        {
            loginInfo = (GONES.Tools.Common.LoginInfo)context.Session["LoginInfo"];
        }
        if (string.IsNullOrEmpty(title))
        {
            failure("无指定操作");
        }
        else
        {
            switch (title)
            {
                case "dbback":
                    if (dbback(dbname, backpath, basepath))
                    {
                        context.Response.Write(success("", "DataBack"));
                    }
                    else
                    {
                        context.Response.Write(failure("数据库连接错误"));
                    }
                    break;
                case "delete":
                    if (Del(context.Request["ids"]))
                    {
                        context.Response.Write(success("", "DataBack"));
                    }
                    else
                    {
                        context.Response.Write(failure(ErrMsg));
                    }
                    break;
            }
        }
    }

    public bool Del(string ids)
    {
        var dbbackManager = appContext.GetObject("S_DbBackUpManager") as GONES.IBLL.IS_DbBackUpManager;
        string[] strs = ids.Split(',');
        try
        {
            foreach (string str in strs)
            {
                dbbackManager.Delete(str);
            }
            return true;
        }
        catch { return false; }
    }

    public bool dbback(string dbname, string backpath, string basepath)
    {  
        try
        {
        var dbbackManager = appContext.GetObject("S_DbBackUpManager") as GONES.IBLL.IS_DbBackUpManager;
        string s = "BACKUP DATABASE {0} to DISK ='{1}' ";
      
            s = string.Format(s, dbname, backpath);
            dbbackManager.dbBackDataBase(s);
            addZipEntry(backpath, basepath);
            return true;
        }
        catch
        {
            return false; 
        }
        
    }



    private GONES.Model.S_DbBackUp GetDbBackModel(string dbfileid, string filename, string filesize)
    {
        var dbbackManager = appContext.GetObject("S_DbBackUpManager") as GONES.IBLL.IS_DbBackUpManager;
        GONES.Model.S_DbBackUp dbback = new GONES.Model.S_DbBackUp();

        if (dbfileid.Trim() != "")
            dbback = dbbackManager.Get(dbfileid.Trim());
        dbback.ID = dbfileid.Trim();
        dbback.FileName = filename.Trim();
        dbback.FileSize = filesize.Trim();
        return dbback;
    }
    public bool Add(string filename, string filesize)
    {
        var dbbackManager = appContext.GetObject("S_DbBackUpManager") as GONES.IBLL.IS_DbBackUpManager;
        GONES.Model.S_DbBackUp dbback = new GONES.Model.S_DbBackUp();
        try
        {
            dbback = GetDbBackModel("",filename, filesize);
            dbback.ID = GONES.Tools.Common.Rnd.Guid.ToString().Trim();
            dbback.CreateUser = loginInfo.UserName.Trim();
            
            dbbackManager.Add(dbback);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public void addZipEntry(string PathStr, string strBaseDir)
    {

        if (File.Exists(PathStr + ".zip"))
            File.Delete(PathStr + ".zip");

        FileStream zipfs = File.Create(PathStr + ".zip");
        ZipOutputStream zos = new ZipOutputStream(zipfs);
        FileInfo fi = new FileInfo(PathStr);
        FileStream fs = File.OpenRead(fi.FullName);
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        string strEntryName = fi.FullName.Replace(strBaseDir, "");
        ZipEntry entry = new ZipEntry(strEntryName);
        zos.PutNextEntry(entry);
        zos.Write(buffer, 0, buffer.Length);
        Add(fi.FullName, (zos.Length / 1024).ToString() + " KB");
        fs.Close();
        zos.Finish();
        zos.Close();
    }

    
    public string success()
    {
        return "{\"statusCode\":\"200\", \"message\":\"操作成功!\"}";
    }
    public string success(string str, string navTabId)
    {
        return "{\"statusCode\":\"200\", \"message\":\"操作成功!" + str + "\",\"navTabId\":\"" + navTabId + "\"}";
    }
    public string failure()
    {
        return "{\"statusCode\":\"300\", \"message\":\"操作失败\"}";
    }
    public string failure(string str)
    {
        return "{\"statusCode\":\"300\", \"message\":\"操作失败!" + str + "\"}";
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}